﻿using System;
using System.Diagnostics;

namespace Modbus.Messages
{
	internal sealed class GetCommEventLogResponse : ModbusMessage
	{
		/// <summary>
		/// 
		/// </summary>
		internal const int BytesBeforeEvents = 6;

		/// <summary>
		/// 
		/// </summary>
		private static readonly byte[] EmptyByteArray = new byte[0];

		private byte   byteCount;
		private short  status;
		private ushort eventCount;
		private ushort messageCount;
		private byte[] events;

		public override void Read(ModbusReader reader)
		{
			base.Read(reader);
			
			this.byteCount = reader.ReadByte();
			this.status = reader.ReadInt16();
			this.eventCount = reader.ReadUInt16();
			this.messageCount = reader.ReadUInt16();

			if (this.byteCount > BytesBeforeEvents)
			{
				this.events = reader.ReadBytes(this.byteCount - BytesBeforeEvents);
			}
			else
			{
				this.events = EmptyByteArray;
			}
		}

		public override void Write(ModbusWriter writer)
		{
			base.Write(writer);

			Debug.Assert(this.events != null, "this.events != null");
			Debug.Assert(this.events.Length <= (UInt16.MaxValue - BytesBeforeEvents),
				"this.events.Length <= (UInt16.MaxValue - BytesBeforeEvents)");

			writer.Write((ushort)(BytesBeforeEvents + this.events.Length));
			writer.Write(this.status);
			writer.Write(this.eventCount);
			writer.Write(this.messageCount);
			writer.Write(this.events);
		}

		public byte ByteCount
		{
			get { return this.byteCount; }
			set { this.byteCount = value; }
		}

		public short Status
		{
			get { return this.status; }
			set { this.status = value; }
		}

		public ushort EventCount
		{
			get { return this.eventCount; }
			set { this.eventCount = value; }
		}

		public ushort MessageCount
		{
			get { return this.messageCount; }
			set { this.messageCount = value; }
		}

		public byte[] Events
		{
			get { return this.events; }
			set { this.events = value; }
		}
	}
}
